//
//  UIViewController+CPAlert.m
//  ChinaPoem
//
//  Created by 赵俊明 on 2019/3/7.
//  Copyright © 2019 赵俊明. All rights reserved.
//

#import "UIViewController+CPAlert.h"

@implementation UIViewController (CPAlert)
- (void)cp_share:(NSString *)shareID image:(UIImage *)image handle:(void(^)(UIActivityType _Nullable activityType,BOOL completed))handler
{
    NSMutableArray *items = [NSMutableArray array];
    if (shareID) {
        NSString *name = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
        [items addObject:[NSString stringWithFormat:@"#%@#", name]];
        [items addObject:shareID];
    }else if(image){
        NSString *name = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
        [items addObject:[NSString stringWithFormat:@"#%@#", name]];
        [items addObject:image];
    }
    
    UIActivityViewController *shareVC = [[UIActivityViewController alloc] initWithActivityItems:items applicationActivities:nil];
    NSMutableArray *exTypes =  [NSMutableArray arrayWithArray:@[ UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypePrint, UIActivityTypePostToTencentWeibo, UIActivityTypeSaveToCameraRoll, UIActivityTypeMessage]];
    
    shareVC.excludedActivityTypes = exTypes;
    [self presentViewController:shareVC animated:YES completion:nil];
    if ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)) {
        UIPopoverPresentationController *popover = shareVC.popoverPresentationController;
        if (popover){
            popover.sourceView = self.navigationController.navigationBar;
            popover.sourceRect = self.navigationController.navigationBar.bounds;
            popover.permittedArrowDirections = UIPopoverArrowDirectionUp;
        }
    }
    
    shareVC.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (handler) {handler(activityType,completed);}
    };
}

- (void)cp_show:(NSString *)title msg:(NSString *)msg cancel:(BOOL)show handle:(void(^)(BOOL isLive))handle
{
    UIAlertController *al = [UIAlertController alertControllerWithTitle:title message:msg preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ac = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (handle) {handle(YES);}
    }];
    
    if (show) {
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        [al addAction:cancle];
    }
    [al addAction:ac];
    [self presentViewController:al animated:YES completion:NULL];
}
@end
